// 原始项目的函数，直接迁移然后兼容

import dayjs from 'dayjs'
import { isEmpty } from 'lodash-es'

/** 原始项目函数 */
export function switchTerm(trem_value: number, productType: number, extraInfo: Record<string, any> | null | undefined) {
  // useConsole?.log('switchTerm', {
  //   trem_value,
  //   productType,
  //   extraInfo,
  // })

  const preDays = extraInfo?.preDays || 0

  let leaseTerm = 0
  if (productType === 7) {
    // 三期2天一结
    leaseTerm = 3
    return leaseTerm
  }
  // 灵活期数
  if (productType === 9 && preDays > 0) {
    return preDays
  }
  // 灵活天数
  if (productType === 8 && preDays > 0) {
    const termDays = trem_value
    const ys = termDays % preDays
    leaseTerm = ys > 0 ? Number.parseInt(`${termDays / preDays}`) + 1 : Number.parseInt(`${termDays / preDays}`)
    return leaseTerm
  }
  if (trem_value < 30) {
    leaseTerm = trem_value
  }
  else if (trem_value === 730) {
    leaseTerm = 24
  }
  else if (trem_value === 365) {
    leaseTerm = 12
  }
  else if (trem_value === 180) {
    leaseTerm = 6
  }
  else if (trem_value === 90) {
    leaseTerm = 3
  }
  else if (trem_value === 60) {
    leaseTerm = 2
  }
  else if (trem_value === 30) {
    leaseTerm = 1
  }
  else {
    leaseTerm = Number.parseInt(`${trem_value / 30}`) + (trem_value % 30 >= 15 ? 1 : 0)
  }
  if (productType === 5) {
    // 15天已结
    leaseTerm = leaseTerm * 2
    return leaseTerm
  }
  return Number(leaseTerm)
}

/** 原始项目函数 */
export function getTermArr(param: any[], productType: number, extraInfo: Record<string, any>) {
  // useConsole?.log('getTermArr', {
  //   param,
  //   productType,
  //   extraInfo,
  // })

  const arr: any[] = []
  param.forEach((item: any) => {
    item.term_list.forEach((term: any) => {
      arr.push(switchTerm(term.value, productType, extraInfo))
    })
  })
  return arr.sort()
}

/** 原始项目函数 */
export function getMinPrice(params: any[] = []) {
  // useConsole?.log('getMinPrice', { params })

  const prices: number[] = []
  for (let i = 0; i < params.length; i++) {
    for (let t = 0; t < params[i].term_list.length; t++) {
      for (let s = 0; s < params[i].term_list[t].specifications.length; s++) {
        const price = Number.parseFloat((params[i].term_list[t].specifications[s].money / params[i].term_list[t].value / 100).toFixed(2))
        prices.push(price)
      }
    }
  }
  const minPrice = Math.min.apply(null, prices)
  const maxPrice = Math.max.apply(null, prices)
  return [minPrice, maxPrice]
}

/** 原始项目函数 */
export function getData(inData: Record<string, any>) {
  const leaseTerm = switchTerm(inData.term.value, inData.productType, inData.extraInfo)

  // #ifdef MP-ALIPAY
  getPrice(inData)
  // #endif

  let data: Record<string, any> = {
    ...inData,
    outPrice: inData.outPrice,
    startDate: dayjs().format('YYYY-MM-DD'),
    endDate: dayjs().add(inData.term.value, 'day').format('YYYY-MM-DD'),
    productId: inData.id,
    leaseTerm,
    productType: inData.productType,
    // 商品图片
    image: inData.slideshows[0],
    // 勾选碎屏传递价格
    spxPrice: inData.spxPrice,
    // 选中碎屏
    isChooseSpx: inData.isChooseSpx,
    // 买断尾款
    worryMoney: inData.worryMoney,
    // 总买断尾款
    worryMoneySum: Number.parseFloat(((inData.worryMoney / 100) * inData.zlnum).toFixed(2)),
    // 押金
    cashSum: (inData.cash * inData.zlnum) / 100,
    // 首付期数
    firstPayPeriod: inData.firstPayPeriod,
    // 押金期数
    cashPeriod: inData.cashPeriod,
    // ?
    // buyProject: inData.buyProject,
    // 配件总价
    pjPrice: (inData.pjModelArr || []).reduce((prev: any, next: any) => prev + next.price, 0) || 0,
  }
  let firstMoney = 'firstMoney' in inData.extraInfo ? inData.extraInfo.firstMoney * inData.zlnum : 0
  console.log('originalData', inData.firstMoney)
  // 自定义首期
  if (firstMoney === 0) {
    if (inData.firstMoney && inData.firstMoney > 0) {
      firstMoney = inData.firstMoney * inData.zlnum
    }
  }

  // 自定义租期比例
  const selfTermPrice = 'selfTermPrice' in inData.extraInfo ? inData.extraInfo.selfTermPrice : {}
  const selfTerm = selfTermPrice[inData.term.value]
  let selfRate = 0.0
  for (const key in selfTerm) {
    if (key.startsWith('key')) {
      selfRate = selfRate + Number(selfTerm[key] || 0)
    }
  }

  // 自定义租金
  const selfTermMoney = 'selfTermMoney' in inData.extraInfo ? inData.extraInfo.selfTermMoney : {}
  const moneyObjs = selfTermMoney[`${inData.term.value}${inData.tit}${inData.packName}`] || {}
  let perSelfMoney = []

  const priceSelfMoney = Object.keys(moneyObjs).filter(it => it.startsWith('key')).map(it => Number(it.split('-')[1])).sort((a, b) => a - b).map(it => moneyObjs[`key-${it}`])
  const sum = priceSelfMoney.reduce((a, b) => a + b, 0)
  if (sum * 100 === inData.money) {
    perSelfMoney = priceSelfMoney
  }

  if (!isEmpty(inData.orderPriceList)) {
    data.priceArray = inData.orderPriceList.map((it: any) => Number(it.price))
    calcFirstRent(data.priceArray, data)
  }
  else if (!isEmpty(perSelfMoney)) {
    data.priceArray = perSelfMoney
    calcFirstRent(perSelfMoney, data)
  }
  else if (selfRate === 100) {
    data = calcSelfPrice(data, firstMoney, selfTerm)
  }
  else {
    data = calcPrice(data, leaseTerm, firstMoney)
  }
  calcRentDate(data)
  console.log('originalData', data)
  // useConsole?.log('original:getData', data)
  return data
}
function getPrice(pakData: Record<string, any>) {
  pakData.cash = pakData.wxCash ? pakData.wxCash : pakData.cash
  pakData.worryMoney = pakData.wxWorryMoney ? pakData.wxWorryMoney : pakData.worryMoney
  // 非线下
  if (pakData.isOffline !== 1) {
    pakData.money = pakData.wxMoney ? pakData.wxMoney : pakData.money
  }
  pakData.buyout = pakData.wxBuyout ? pakData.wxBuyout : pakData.buyout

  return pakData
}
function calcPrice(data: Record<string, any> = {}, leaseTerm: number, firstMoney: any) {
  const totalPrice = data.money * data.zlnum
  const newLeaseTerm = leaseTerm - (firstMoney > 0 ? 1 : 0)

  // 余数
  const remainPrice = (totalPrice - firstMoney) % newLeaseTerm
  const priceEver = (totalPrice - firstMoney - remainPrice) / newLeaseTerm

  data.dayRent = Number.parseFloat((totalPrice / data.term.value / 100).toFixed(2))

  // 尾期租金
  const lastRent = Number.parseFloat((priceEver / 100 + remainPrice / 100).toFixed(2))
  const priceArray = Array.from({ length: leaseTerm })
  for (let i = 0; i < priceArray.length; i++) {
    // 最后一期价格
    if (i === priceArray.length - 1) {
      priceArray[i] = lastRent
      break
    }
    // 前11期价格
    priceArray[i] = Number.parseFloat((((i === 0 && firstMoney > 0) ? firstMoney : priceEver) / 100).toFixed(2))
  }
  calcFirstRent(priceArray, data)
  return data
}
function calcSelfPrice(data: any, firstMoney: any, selfTermPrice: any) {
  const totalPrice = data.money * data.zlnum
  let priceAll = Number(totalPrice)
  // 自定义每期比例
  let fractionalPart = 0
  // 取出每期比例
  const rateArr = []
  let j = 0
  const keys = Object.keys(selfTermPrice).filter(it => it.startsWith('key'))
  for (const key of keys
    .map(it => Number(it.split('-')[1]))
    .sort()
    .map(it => `key-${it}`)) {
    if (key.startsWith('key')) {
      rateArr[j] = selfTermPrice[key]
      j++
    }
  }
  const priceArray = Array.from({ length: rateArr.length })
  // 设置了首期租金，把第一期比例评分给剩余期数
  const size = rateArr.length
  if (firstMoney > 0) {
    const rate0 = rateArr[0]
    const remainSize = size - 1
    if (remainSize > 0) {
      priceAll = priceAll - firstMoney
      const remainRate = rate0 % remainSize
      const perRate = (rate0 - remainRate) / remainSize
      for (let i = 0; i < remainSize; i++) {
        if (i === remainSize - 1) {
          rateArr[i + 1] = Number(rateArr[i + 1]) + Number(perRate) + Number(remainRate)
        }
        else {
          rateArr[i + 1] = Number(rateArr[i + 1]) + Number(perRate)
        }
      }
    }
  }
  for (let i = 0; i < size; i++) {
    if (firstMoney > 0 && i === 0) {
      priceArray[i] = firstMoney
      continue
    }
    // 计算总租金*每期比例金额
    const price = Number((priceAll * rateArr[i]) / 100)
    // 整数部分
    const integerPart = price
    // 小数部分
    fractionalPart = price - price
    if (i === priceArray.length - 1) {
      priceArray[i] = integerPart + fractionalPart
    }
    else {
      priceArray[i] = integerPart
    }
  }
  for (let i = 0; i < priceArray.length; i++) {
    priceArray[i] = Number.parseFloat((Number(priceArray[i]) / 100).toFixed(2))
  }

  data.totalPrice = priceAll
  data.newLeaseTerm = selfTermPrice.leaseTerm
  data.meiqiPrice = priceArray[priceArray.length - 2]

  // 尾期租金
  data.lastRent = priceArray[priceArray.length - 1]

  data.firstMoney = priceArray[0]
  data.priceArray = priceArray

  calcFirstRent(priceArray, data)

  return data
}
function calcFirstRent(priceArray: any, data: Record<string, any>) {
  data.priceArray = priceArray
  let firstRent = 0
  for (let i = 0; i < priceArray.length; i++) {
    if (i < data.firstPayPeriod) {
      firstRent += Number(priceArray[i])
    }
  }
  // 首付租金
  data.firstRent = Number.parseFloat(firstRent.toFixed(2))
}
function calcRentDate(data: Record<string, any>) {
  const addYsDate = dayjs().add(data.ysDay || 0, 'days')
  let currentDate = addYsDate.format('YYYY-MM-DD')
  // 获取当前月份天
  const d = addYsDate.date()
  if (d > 28) {
    // 获取当前日期
    const now = dayjs()
    // 获取下个月的第一天
    const nextMonthFirstDay = now.endOf('month').add(1, 'day').startOf('month')
    currentDate = nextMonthFirstDay.format('YYYY-MM-DD')
  }
  const orderPriceList = data.priceArray

  const rentUnit = data.term.value < 30 ? 'days' : 'months'

  for (let i = 0; i < orderPriceList.length; i++) {
    orderPriceList[i] = { price: orderPriceList[i] }
    const date = dayjs(currentDate, 'YYYY-MM-DD')
    orderPriceList[i].date = date.add(i, rentUnit).format('YYYY-MM-DD')
  }
  data.orderPriceList = orderPriceList
}
